<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionEndedMoreLines{
	
	function QuestionEndedMoreLines(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){						
		$return_content_array = array();
		$return = "";
		$answer = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$value = "";
		$entered = "";
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($question_id, $question_details["0"]["title"], $answers);					
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		if(count($answers)>0){
			$edit_values = $this->getValue($question_id, $session_id);
			$all_values = array();
			foreach($edit_values as $key=>$edit_val){
				$all_values[$edit_val["q_id"]."_".$edit_val["a_id"]] = $edit_val["value"];
			}			
			foreach($answers as $key=>$value){
				$val = "";
				if(isset($all_values[$question_id."_".$value["id"]])){
					if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
						$val = $all_values[$question_id."_".$value["id"]];
					}
				}
				$return .= 	  '<tr>';
				$return .= 	  	 '<td>';
				$return .= 	  	    '<span class="'.$params->answer.'">'.$value["value"].'</span>&nbsp;';
				$return .= 	  	 '</td>';
				$return .= 	  	 '<td>';				
				$return .= 	  	    '<input type="text" class="" value="'.$val.'" name="question['.$question_id.'][answer]['.$value["id"].']" id="a'.$value["id"].'"> &nbsp;';
				$return .= 	  	 '</td>';
				$return .= 	  '</tr>';		
			}
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td>';
		$return .= 	  	    '<input type="hidden" value="moreline" name="question['.$question_id.'][type]">';
		$return .= 	  	    '<input type="hidden" value="open" name="question['.$question_id.'][orientation]">';
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';
		
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="'.$value.'">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionEndedMoreLines">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function createValidation($question_id, $title, $answers){
		$result = "";
		
		if(count($answers)>0){
			foreach($answers as $key=>$value){
				$result .= '	if (document.survey_content.a'.$value["id"].'.value.length==0){'."\n".
						   '		alert(AlertText +"'.addslashes(trim($title)).'");'."\n".
						   '		return false;'."\n".
						   '	}'."\n";
			}
		}					
		return $result;
	}
	
	function save($id, $type, $session_id){
		$db =& JFactory::getDBO();		
		$all_answers = JRequest::getVar("question");
		$answers = $all_answers[$id]["answer"];
		
		if($this->answerExist($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;												
			$db->setQuery($sql);
			$db->query();
		}
		
		foreach($answers as $key=>$value){
			if(trim($value) != ""){
				$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
				$sql .= $id.", ".$key.", 0, 0, ".$session_id.", '".addslashes($value)."'";
				$sql .= ")";
				$db->setQuery($sql);
				$db->query();
			}
		}
	}
	
	function answerExist($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
		
	function getValue($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_result');
		$query->where("q_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$controller = JRequest::getVar("controller", "", "get");		
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="4" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td></td>';
		$return .= 			'<td></td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_RESPONSE_PERCENT");
		$return .= 			'</td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_TOTAL_RESPONSE");	
		$return .= 			'</td>';				
		$return .= 		'</tr>';
		$k = 0;
		foreach($answers as $a_key=>$a_value){
			$class = $params->table_row1;
			if($k%2 != 0){
				$class = $params->table_row2;
			}
			$k++;
			$count 	 = $this->countTotal($a_value["id"]);
			$return .= '<tr class="'.$class.'">';
			$return .= 		'<td align="right" style="padding-right:5px;">';
			$app =& JFactory::getApplication();      	
			if($app->isAdmin()){
				if($controller != "" && $controller == "statistics"){
					$r_id = JRequest::getVar("r_id", "0");
					$link = JURI::root().'administrator/index.php?option=com_surveys&controller=editdetails&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]."&r_id=".$r_id;
					$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
				}				
			}
			else{
				$link = JRoute::_('index.php?option=com_surveys&controller=editsurvey&Itemid='.JRequest::getVar("Itemid").'&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]);
				$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
			}		
			$return .= 			$a_value["value"];
			$return .= 		'</td>';			
			$return .= 		'<td align="left" width="30%">';
			if(intval($all_responses_count) != "0"){
				$return .= 		@$this->getPicture(number_format( (($count * 100) / $all_responses_count), 2, '.', '') );
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			if(intval($all_responses_count) != "0"){			
				$return .= 		@number_format( (($count * 100) / $all_responses_count), 2, '.', '') . " %";
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			$return .= 			$count;			
			$return .= 		'</td>';				
			$return .= '</tr>';	
		}
		$return .= 		'<tr>';
		$return .= 			'<td colspan="3" style="padding-right:5px;" align="right">';
		$return .= 				'<b>'.JTExt::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
		$return .= 			'</td>';
		$return .= 			'<td class="'.$params->total_background.'" align="center">';
		$return .= 				'<b>'.$this->countPerQuestion($id).'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= '</table>';
		return $return;		
	}	
	
	function countTotal($a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where a_id=".$a_id.$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countPerQuestion($id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$id." group by session_id".$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function getPicture($value){		   
		$picture = "";
		$picture .= "<div style=\"width:100%;\">";
		$picture .= 	"<div style=\"width:" . $value . "%; background-color:#0000CC;\"> &nbsp; ";
		$picture .= 	"</div>";
		$picture .= "</div>";
		return $picture;
	}
	
	function getForHeader($id, $title){		
		return $title;
	}
	
	function getForRow($q_id, $sess_id){
		$answers = $this->getAnswers($q_id);
		$result_array = array();
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($sess_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		if($result == NULL || count($result) == 0){
			return "NO ANSWER";
		}
		else{
			foreach($result as $key=>$value){
				$result_array[] = trim($value["answer_value"])." - ".$value["result_value"];
			} 
		}
		return implode(" AND ", $result_array);
	}
	
	function getQuestionResultForEmail($q_id, $session_id, $title){		
		$return = $title.":"."\n";
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($session_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		
		foreach($result as $key=>$value){
			$return .= "\t".trim($value["answer_value"]).": ".trim($value["result_value"]);
			$return .= "\n";
		}
		return $return;
	}	
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;
		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($value, $skip_answer)){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
};

?>